<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button type="danger" size="small" @click="putExcel">导入excel</el-button>
          <el-button type="success" size="small" @click="handleDownload">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工
          </el-button>
        </template>
      </page-tools>
      <!-- 新增员工弹框组件 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" width="50%" @close="closeDialog">
        <emp-dialog ref="addEmpt" @addCanel="addCanel" @addEmployee="addEmployee" />
      </el-dialog>
      <el-card style="margin-top: 10px;" class="employees-list">
        <el-table :data="employeesList" style="width:100%" :default-sort="{prop: 'workNumber'}" border>
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column label="头像" width="80">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" class="staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" :formatter="formatter" sortable label="聘用形式" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column sortable label="入职时间">
            <template slot-scope="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="correctionTime" label="转正时间" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分配角色弹框 -->
        <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="50%"
        >
          <assign-role v-if="dialogVisible" :assign-roleid="assignRoleid" @close="dialogVisible = false" />
        </el-dialog>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { getEmployeeList, delEmployeeList } from '@/api/employees'
import empDialog from './empDialog.vue'
import EmployeeEnum from '@/constant/employees'
import AssignRole from './assignRole.vue'
export default {
  name: 'Employees',
  components: { empDialog, AssignRole },
  filters: {
    // 格式化入职日期的方法
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      total: 0, // 数据总条数
      employeesList: [], // 员工列表
      showDialog: false,
      dialogVisible: false, // 分配角色
      assignRoleid: '' // 分配角色id
    }
  },
  created() {
    this.getEmployeeList()
  },

  methods: {
    async getEmployeeList() {
      const res = await getEmployeeList(this.query)
      // console.log(res)
      this.employeesList = res.data.rows
      console.log(this.employeesList)
      this.total = res.data.total
    },
    // 每页显示的条数发生改变时触发z
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    },
    // 聘用形式
    formatter(row, column, cellValue, index) {
      // 用数组的 find 方法找到 id = 1 的元素，再取出它的 value
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 删除员工
    async delEmp(id) {
      // 显示删除询问对话框
      const delRes = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 用户点击了取消，给用户进行提示
      if (delRes === 'cancel') return this.$message('您取消了删除')
      const res = await delEmployeeList(id)
      console.log(res)
      // 删除成功后的提示
      this.$message.success(res.message)
      // 重新获取数据
      this.getEmployeeList()
    },
    // 取消新增
    addCanel() {
      this.showDialog = false
    },
    // 确定添加之后
    addEmployee() {
      this.showDialog = false
      this.getEmployeeList()
    },
    // 关闭弹框时销毁数据
    closeDialog() {
      this.$refs.addEmpt.resetForm()
    },
    // 导入excel
    putExcel() {
      this.$router.push('/excel')
    },
    transData(rows) {
      // 写代码
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 格式化文档
      const headerArr = Object.keys(rows[0])
      const header = headerArr.map(item => {
        return map[item]
      })
      // 格式化具体数据
      const data = rows.map(item => {
        return Object.values(item)
      })
      return { header, data }
    },
    // 导出excel
    async  handleDownload() {
      const res = await getEmployeeList(this.query)
      const excelObj = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 分配角色
    setRole(id) {
      this.dialogVisible = true
      this.assignRoleid = id
    }
    // 关闭分配角色弹框
    // closerole() {
    //   this.dialogVisible = false
    // }
  }

}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}</style>
